package cc.linker.steplink.crm.merchanth5.service;

import cc.linker.steplink.crm.commons.CrmRedisKeys;
import cc.linker.steplink.crm.commons.enums.IntegralEnums;
import cc.linker.steplink.crm.commons.form.FormRequest;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.lock.LettuceLock;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.commons.utils.TransactionOrderUtil;
import cc.linker.steplink.crm.merchanth5.dao.MaiBaoLaDao;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.dao.integral.IntegralH5Dao;
import cc.linker.steplink.crm.merchanth5.model.OrderAddressDto;
import cc.linker.steplink.crm.merchanth5.pojo.*;
import cc.linker.steplink.crm.merchanth5.service.acs.ProtectRecordService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.merchanth5.service.coupon.CouponH5Service;
import cc.linker.steplink.crm.merchanth5.service.impl.PurchaseProcessNewServiceImpl;
import cc.linker.steplink.crm.merchanth5.service.integral.IntegralH5Service;
import cc.linker.steplink.crm.merchanth5.service.redis.GoodsService;
import cc.linker.steplink.crm.merchanth5.service.redis.MerchantService;
import cc.linker.steplink.crm.merchanth5.service.tl.LedgerProcessService;
import cc.linker.steplink.crm.merchanth5.util.ParamSignUtils;
import cc.linker.steplink.crm.merchanth5.util.Timer.TimerContext;
import cc.linker.steplink.crm.merchanth5.util.Timer.TimerScheduler;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class MallService {
    @Autowired
    private MallDao mallDao;
    @Autowired
    private MallBoomDao mallBoomDao;
    @Autowired
    private MaiBaoLaService maiBaoLaService;
    @Autowired
    private MaiBaoLaDao maiBaoLaDao;
    @Autowired
    private SmsService smsService;
    @Autowired
    private ProtectRecordService protectRecordService;
    @Autowired
    private PurchaseProcessService purchaseProcessService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CommonsService commonsService;
    @Autowired
    private LedgerProcessService ledgerProcessService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private CouponH5Service couponH5Service;
    @Autowired
    private CustomerIntegralService customerIntegralService;
    @Autowired
    private IntegralH5Dao integralH5Dao;
    @Autowired
    private IntegralH5Service integralH5Service;
    @Autowired
    private FormRequest formRequest;

    public Object getGoodsList(Map<String, Object> params) {
        int pageIndex = 1, pageSize = 20;
        Object pi = params.get("pageIndex");
        if (pi instanceof Integer && (int) pi >= 0) {
            pageIndex = (int) pi;
        }
        Object ps = params.get("pageSize");
        if (ps instanceof Integer && (int) ps >= 0) {
            pageSize = (int) ps;
        }
        PageInfo result;
        String listGoodsStr = redisTemplate.opsForValue().get("home:mall_goods_list" + cc.linker.steplink.crm.commons.utils.StringUtil.getStringByMap(params));
        if (StringUtils.isEmpty(listGoodsStr)) {
            PageHelper.startPage(pageIndex, pageSize);
            List<MallGoodsPo> goodsList = mallDao.getMerchantGoodsList(params);
            if (goodsList != null && goodsList.size() > 0) {
                for (MallGoodsPo mallGoods : goodsList) {
                    if (mallGoods.getIsSeckill() == 1) {
                        this.getKillThings(mallGoods);
                    }
                }
            }
            result = new PageInfo(goodsList);
            redisTemplate.opsForValue().set("home:mall_goods_list" + cc.linker.steplink.crm.commons.utils.StringUtil.getStringByMap(params), com.alibaba.fastjson.JSON.toJSONString(result), 15, TimeUnit.SECONDS);
        } else {
            result = com.alibaba.fastjson.JSON.parseObject(listGoodsStr, PageInfo.class);
        }
        return result;
    }

    public void getKillThings(MallGoodsPo mallGoods) {
        try {
            Map<String, Object> seckillMap;
            String seckillMapStr = stringRedisTemplate.opsForValue().get("goodsSeckill:" + mallGoods.getGoodsId().toString());
            if (StringUtils.isEmpty(seckillMapStr)) {
                seckillMap = mallDao.getSeckillByGoodsId(mallGoods.getGoodsId().toString());
                stringRedisTemplate.opsForValue().set("goodsSeckill:" + mallGoods.getGoodsId().toString(), com.alibaba.fastjson.JSON.toJSONString(seckillMap, SerializerFeature.WriteMapNullValue), 15, TimeUnit.SECONDS);
            } else {
                seckillMap = (Map<String, Object>) com.alibaba.fastjson.JSON.parse(seckillMapStr);
                SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                seckillMap.put("startTime", df2.format(new Date(Long.parseLong(seckillMap.get("startTime").toString()))));
                seckillMap.put("endTime", df2.format(new Date(Long.parseLong(seckillMap.get("endTime").toString()))));
            }
            if (seckillMap != null && seckillMap.size() > 0) {
                String startTime = seckillMap.get("startTime").toString();
                String endTime = seckillMap.get("endTime").toString();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date sd1 = df.parse(startTime);
                Date sd2 = df.parse(endTime);
                Date nowDate = new Date();
                mallGoods.setSeckillAllSecond((sd2.getTime() - sd1.getTime()) / 1000);
                if (sd1.after(nowDate)) {
                    //未开始
                    mallGoods.setSeckillStatus(0);
                    mallGoods.setSeckillSecond((sd1.getTime() - nowDate.getTime()) / 1000);
                } else if (nowDate.after(sd2)) {
                    //已结束
                    mallGoods.setSeckillStatus(2);
                    mallGoods.setSeckillSecond((nowDate.getTime() - sd2.getTime()) / 1000);
                } else {
                    //进行中
                    mallGoods.setSeckillStatus(1);
                    mallGoods.setSeckillSecond((sd2.getTime() - nowDate.getTime()) / 1000);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Modify: wuyue
     * @Date: 2019/9/5 10:58
     * @Description: 点击记录
     * @Version: v1.8.3
     */
    public Object getGoodsInfo(Map<String, Object> params) {
        if (params.containsKey("customerId") && params.containsKey("customerId")) {
            params.put("objectId", Long.valueOf(params.get("goodsId").toString()));
            this.addToDealData(params, 2);
        }
        // 主业务，商品详情
        MallGoodsPo merchantGoodsInfo = mallDao.getMerchantGoodsInfo(params);
        maiBaoLaService.judgeDeleteOrBanned(merchantGoodsInfo);
        if (params.get("source") != null) {
            String source = params.get("source").toString();
            if ("dong".equals(source) && merchantGoodsInfo.getDongGoodsStatus() != 1) {
                throw GlobalException.build("商品已下架");
            }
        }
        if (params.get("goodsId") != null) {
            String filePath = redisTemplate.opsForValue().get("idp_sourceImg_" + params.get("goodsId").toString());
            if (StringUtil.isNotEmpty(filePath)) {
                merchantGoodsInfo.setGoodsPreview(filePath);
            }
        }
        if (merchantGoodsInfo.getIsSeckill() == 1) {
            this.getKillThings(merchantGoodsInfo);
        }
        return merchantGoodsInfo;
    }

    public Object getGoodsSku(Map<String, Object> params) {
        return goodsService.getGoodsSku(params.get("goodsId").toString());
    }

    public Object getGoodsSpec(Map<String, Object> params) {
        return goodsService.getGoodsSpec(params.get("goodsId").toString());
    }

    public Map<String, Object> convertBeanToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    if (null == value) {
                        map.put(key, "");
                    } else {
                        map.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
        }
        return map;
    }

    public Object getShoppingCart(Map<String, Object> params) {
        List<ShoppingCartPo> userShoppingCart = mallDao.getUserShoppingCart(params);
        List li = new ArrayList();
        for (ShoppingCartPo da : userShoppingCart) {
            Map<String, Object> res = new HashMap<>();
            res.put("merchantId", da.getMerchantId());
            res.put("customerId", da.getCustomerId());
            List<ShoppingCartGoodsPo> goodsList = da.getGoodsList();
            List gli = new ArrayList();
            for (ShoppingCartGoodsPo gl : goodsList) {
                Map<String, Object> glRes = convertBeanToMap(gl);
                glRes.put("amount", NumberUtils.fenToYuan(gl.getAmountCent()));
                gli.add(glRes);
            }
            res.put("goodsList", gli);
            li.add(res);
        }
        return li;
//        return mallDao.getUserShoppingCart(params);
    }

    public Object getShoppingCartNew(Map<String, Object> params) {
        boolean isVip = false;
        if (params.containsKey("isVip") && !StringUtils.isEmpty(params.get("isVip")) && "1".equals(params.get("isVip").toString())) {
            isVip = true;
        }
        List<Map> merchantMaps = mallDao.getMerchant(params);
        if (merchantMaps != null && merchantMaps.size() > 0) {
            for (Map map : merchantMaps) {
                Long merchantId = null;
                if (map.get("merchantId") != null) {
                    merchantId = Long.valueOf(map.get("merchantId").toString());
                }
                params.put("merchantId", merchantId);
                List<ShoppingCartPo> list = mallDao.getUserShoppingCart(params);
                for (ShoppingCartPo shoppingCartPo : list) {
                    if (shoppingCartPo.getGoodsList() != null && shoppingCartPo.getGoodsList().size() > 0) {
                        List<ShoppingCartGoodsPo> goodsList = shoppingCartPo.getGoodsList();
                        for (ShoppingCartGoodsPo shoppingCartGoodsPo : goodsList) {
                            if (shoppingCartGoodsPo.getIsSeckill() != null && shoppingCartGoodsPo.getIsSeckill() == 1) {
                                Map seckillMap = mallDao.getSeckillByGoodsId(shoppingCartGoodsPo.getGoodsId().toString());
                                Integer seckillStatus = 0;
                                try {
                                    if (seckillMap != null) {
                                        String startTime = seckillMap.get("startTime").toString();
                                        String endTime = seckillMap.get("endTime").toString();
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        Date sd1 = df.parse(startTime);
                                        Date sd2 = df.parse(endTime);
                                        Date nowDate = new Date();
                                        if (sd1.after(nowDate)) {
                                            //未开始
                                            seckillStatus = 0;
                                        } else if (nowDate.after(sd2)) {
                                            //已结束
                                            seckillStatus = 2;
                                        } else {
                                            //进行中
                                            seckillStatus = 1;
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                shoppingCartGoodsPo.setSeckillStatus(seckillStatus);
                            }
                            Integer quota = maiBaoLaService.quota(shoppingCartGoodsPo.getGoodsId().toString(),shoppingCartPo.getCustomerId());
                            shoppingCartGoodsPo.setQuotaNum(quota);
                        }
                    }
                }
                if (list.size() > 0) {
                    map.put("goodsList", list.get(0).getGoodsList());
                } else {
                    map.put("goodsList", new ArrayList<ShoppingCartGoodsPo>());
                }
            }
        }
        //return mallDao.getUserShoppingCart(params);
        return merchantMaps;
    }


    public void addShoppingCart(Map<String, Object> params) {

        if (params.containsKey("distributor") && StringUtils.isEmpty(params.get("distributor"))) {
            params.remove("distributor");
        }
        if (params.containsKey("author") && StringUtils.isEmpty(params.get("author"))) {
            params.remove("author");
        }
        ShoppingCartGoodsPo shoppingCartGoodsPo = null;
        if (null != params.get("skuId")) {
            if ("".equals(params.get("skuId")) || "0".equals(params.get("skuId").toString())) {
                shoppingCartGoodsPo = mallDao.getShoppingCartMerchantGoodsByGoods(params);
            } else {
                shoppingCartGoodsPo = mallDao.getShoppingCartMerchantGoodsByGoodsSku(params);
            }
        }
        Integer buyCount = (Integer) params.get("buyCount");
        String customerId = (String) params.get("customerId");
        String goodsId = params.get("goodsId").toString();

        Integer quota = maiBaoLaService.quota(goodsId, customerId);
        if (quota == -3) {
            throw GlobalException.build("您不满足购买条件");
        }
        Integer cartBuyNum = mallDao.countCartBuyNum(params);
        if (cartBuyNum + buyCount > quota && quota != -1) {
            throw GlobalException.build("超过限购上限");
        }
        //判断是否是“秒杀商品”
        Integer isSeckill = mallDao.getIsSeckillByGoodsId(goodsId);
        if (isSeckill == 1) {
            throw GlobalException.build("秒杀商品不能加入购物车！");
        }
        //判断是否是“虚拟商品”
        Integer isVirtual = mallDao.getIsVirtualByGoodsId(goodsId);
        if (isVirtual == 1) {
            throw GlobalException.build("虚拟商品不能加入购物车！");
        }
        if (shoppingCartGoodsPo != null) {
            params.put("shoppingCartId", shoppingCartGoodsPo.getShoppingCartId());
            if (shoppingCartGoodsPo.getGoodsCount() <= (shoppingCartGoodsPo.getBuyCount() + buyCount)) {
                params.put("buyCount", shoppingCartGoodsPo.getGoodsCount());
            } else {
                params.put("buyCount", (shoppingCartGoodsPo.getBuyCount() + buyCount));
            }
            mallDao.editShoppingCart(params);
        } else {
            //根据商品id获取商户id
            Map<String, Object> storeMap = mallDao.getMerchantIdByGoodsId(goodsId);
            Long merchantId = null;
            if (null != storeMap.get("merchantId")) {
                merchantId = Long.valueOf(storeMap.get("merchantId").toString());
            }
            params.put("merchantId", merchantId);
            mallDao.addShoppingCart(params);
        }
    }

    public Integer killLimit(String goodsId, String customerId) {
        //如果是则判断是否在有效期和是否是在会员等级区间
        LOGGER.info("判断商品是否满足秒杀条件，商品id为" + goodsId);
        Map seckillMap = mallDao.getSeckillByGoodsId(goodsId);
        //startTime, endTime, vipLimitStart, viPlimitEnd
        String msg = "";
        Integer seckillStatus = 0;
        try {
            if (seckillMap != null) {
                String startTime = seckillMap.get("startTime").toString();
                String endTime = seckillMap.get("endTime").toString();
                Integer vipLimitStart = 0;
                if (!StringUtils.isEmpty(seckillMap.get("vipLimitStart"))) {
                    vipLimitStart = Integer.valueOf(seckillMap.get("vipLimitStart").toString());
                }
                Integer viPlimitEnd = 9;
                if (!StringUtils.isEmpty(seckillMap.get("viPlimitEnd"))) {
                    viPlimitEnd = Integer.valueOf(seckillMap.get("viPlimitEnd").toString());
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date sd1 = df.parse(startTime);
                Date sd2 = df.parse(endTime);
                Date nowDate = new Date();
                if (sd1.after(nowDate)) {
                    msg = "活动未开始！";
                    throw GlobalException.build("活动未开始！");
                }
                if (sd2.before(nowDate)) {
                    msg = "活动已结束！";
                    throw GlobalException.build("活动已结束！");
                }
                //判断会员等级(0-9不用判断)
                if (vipLimitStart > 0 || viPlimitEnd < 9) {
                    //获取当前用户等级
                    Integer vipLevel = mallDao.getVipLevel(customerId);
                    if (vipLevel > viPlimitEnd || vipLevel < vipLimitStart) {
                        msg = "您的等级未达到要求！";
                        throw GlobalException.build("您的等级未达到要求！");
                    }
                }
                String vipIds = "";
                if (!StringUtils.isEmpty(seckillMap.get("vipIds"))) {
                    vipIds = seckillMap.get("vipIds").toString();
                    Integer vipIdsCount = mallDao.getVipIdCount(customerId, vipIds);
                    if (vipIdsCount == 0) {
                        String vipName = mallDao.getVipName(vipIds);
                        msg = "未开通权益卡" + vipName;
                        throw GlobalException.build("未开通权益卡" + vipName);
                    }

                }

                if (sd1.after(nowDate)) {
                    //未开始
                    seckillStatus = 0;
                } else if (nowDate.after(sd2)) {
                    //已结束
                    seckillStatus = 2;
                } else {
                    //进行中
                    seckillStatus = 1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (!StringUtils.isEmpty(msg)) {
                throw GlobalException.build(msg);
            }
        }
        return seckillStatus;
    }

    public Object editShoppingCart(Map<String, Object> params) {
        Object result;
        String customerId = (String) params.get("customerId");
        ShoppingCartGoodsPo shoppingCartGoodsPo = mallDao.getShoppingCartMerchantGoodsById(params);
        Integer buyCount = (Integer) params.get("buyCount");
        if (shoppingCartGoodsPo == null) {
            return null;
        } else if (shoppingCartGoodsPo.getGoodsCount() <= buyCount) {
            result = shoppingCartGoodsPo.getGoodsCount();
            buyCount = shoppingCartGoodsPo.getGoodsCount();
            params.put("buyCount", shoppingCartGoodsPo.getGoodsCount());
        } else {
            result = params.get("buyCount");
        }
        if (buyCount > shoppingCartGoodsPo.getBuyCount()) {
            Long goodsId = shoppingCartGoodsPo.getGoodsId();
            Integer quota = maiBaoLaService.quota(goodsId.toString(), customerId);
            if (quota == -3) {
                throw GlobalException.build("您不满足购买条件");
            }
            params.put("goodsId", goodsId);
            Integer cartBuyNum = mallDao.countCartBuyNum(params);
            if (cartBuyNum + buyCount > quota && quota != -1) {
                throw GlobalException.build("超过限购上限");
            }
        }
        mallDao.editShoppingCart(params);
        return result;
    }

    public void delShoppingCart(Map<String, Object> params) {
        mallDao.delShoppingCart(params);
    }

    public void delAllShoppingCart(Map params) {
        mallDao.delAllShoppingCart(params);
    }

    public Object checkShoppingOrder(Map<String, Object> params) {
        List<ShoppingCartPo> shoppingCartPos;
        CheckMerchantOrderPo orderPo = new CheckMerchantOrderPo();
        try {
            Integer goodsNum = 0;
            Double goodsAmount = 0.00;
            Double orderAmount = 0.00;
            Double orderTotalPrice = 0.00;
            Double goodsFreight = 0.00;
            List<ShoppingCartGoodsPo> goodsPoList = new ArrayList<>();
            if (params.get("shoppingCartIds") != null) {
                orderPo.setType(1);
                shoppingCartPos = mallDao.checkShoppingCartOrder(params);
                for (ShoppingCartPo cartPo : shoppingCartPos) {
                    for (ShoppingCartGoodsPo goodsPo : cartPo.getGoodsList()) {
                        goodsNum = goodsNum + goodsPo.getBuyCount();
                        goodsAmount = goodsAmount + goodsPo.getAmount() * goodsPo.getBuyCount();
                        orderAmount = orderAmount + goodsPo.getAmount() * goodsPo.getBuyCount();
                        orderTotalPrice = orderTotalPrice + goodsPo.getAmount() * goodsPo.getBuyCount();
                        if (goodsPo.getGoodsFreight() > goodsFreight) {//取运费最大
                            goodsFreight = goodsPo.getGoodsFreight();
                        }
                        if (!StringUtils.isEmpty(goodsPo.getBelongId())) {
                            orderPo.setType(0);
                        }
                    }
                }
                if (shoppingCartPos.size() > 0) {
                    goodsPoList = shoppingCartPos.get(0).getGoodsList();
                }
            } else {
                ShoppingCartGoodsPo goodsPo = mallDao.checkShoppingGoodsOrder(params);
                if (StringUtils.isEmpty(goodsPo.getBelongId())) {
                    orderPo.setType(1);
                } else {
                    orderPo.setType(0);
                }
                goodsPo.setBuyCount((Integer) params.get("buyCount"));
                goodsNum = goodsNum + goodsPo.getBuyCount();
                goodsAmount = goodsAmount + goodsPo.getAmount() * goodsPo.getBuyCount();
                orderAmount = orderAmount + goodsPo.getAmount() * goodsPo.getBuyCount();
                orderTotalPrice = orderTotalPrice + goodsPo.getAmount() * goodsPo.getBuyCount();
                goodsFreight = goodsPo.getGoodsFreight();
                goodsPoList.add(goodsPo);
            }

            orderTotalPrice = orderTotalPrice + goodsFreight;
            orderAmount = orderAmount + goodsFreight;
            orderPo.setGoodsAmount(new BigDecimal(goodsAmount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            orderPo.setOrderAmount(new BigDecimal(orderAmount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            orderPo.setOrderTotalPrice(new BigDecimal(orderTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            orderPo.setGoodsNum(goodsNum);
            orderPo.setShippingFee(new BigDecimal(goodsFreight).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            if (goodsPoList.size() > 0) {
                orderPo.setGoodsList(goodsPoList);
            }
            return orderPo;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public OrderAddressDto getDefaultReceiveAddress(Map<String, Object> params) {
        return mallDao.getDefaultReceiveAddress(params);
    }

    public Object getReceiveAddressList(Map<String, Object> params) {
        return mallDao.getReceiveAddressList(params);
    }

    public void saveReceiveAddress(Map<String, Object> params) {
        Long addressId = StringUtils.isEmpty(params.get("addressId")) ? null : Long.parseLong(params.get("addressId").toString());
        params.put("areaInfo", (String) params.get("provinceName") + params.get("cityName") + params.get("areaName"));
        if (Integer.parseInt(params.get("isDefault").toString()) == 1) {
            mallDao.setReceiveAddressUndefault(params);
        }
        if (addressId != null) {
            mallDao.updateReceiveAddress(params);
        } else {
            mallDao.addReceiveAddress(params);
        }
    }

    public void delReceiveAddress(Map<String, Object> params) {
        mallDao.delReceiveAddress(params);
    }


    @Autowired
    private LettuceLock lettuceLock;

    @Value("${wcpay.payurl}")
    private String payurl;

    public Object createGoodsPayOrderNo(HttpServletRequest request, Long addressId,
                                        Long goodsId, Integer goodsNum,
                                        Integer payType, Long skuId,
                                        String customerId, List<String> shoppingCartIds,
                                        String orgId, String payTradeId,
                                        String openId, String wxpayType, String notifyUrl,
                                        String distributor) throws GlobalException {
        SortedMap<String, Object> finalpackage = new TreeMap<>();
        Map<String, Object> paramsMap = new HashMap<>();
        boolean lock = false;
        boolean cutTag = false;
        List<MerchantOrderPo> orderPos = new ArrayList<>();
        String requestId = UUID.randomUUID().toString();
        String lockKey = "buyMallGoods_" + customerId + "_" + goodsId;
        //        try {
        lock = lettuceLock.tryLock(lockKey, requestId, 2, TimeUnit.MINUTES);
        if (lock) {
            if (payType == 2) {//微信支付
                paramsMap.put("addressId", addressId);
                paramsMap.put("customerId", customerId);
                OrderAddressDto orderAddressDto = mallDao.getDefaultReceiveAddress(paramsMap);
                if (orderAddressDto == null) {
                    throw GlobalException.build("地址不存在或用户与地址不匹配");
                }
                Long orderId = null;
                //商户订单号
                String orderSn = "";
                //支付订单号
                String paySn = "";
                //获取微信支付配置
                //订单总价
                Long totalFee = 0L;
                if (goodsId != null) {//直接购买商品
                    orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
                    paySn = orderSn;
                    paramsMap.put("goodsId", goodsId);
                    paramsMap.put("skuId", skuId);
                    paramsMap.put("goodsNum", goodsNum);
                    ShoppingCartGoodsPo goodsPo = mallDao.getShoppingGoodsInfo(paramsMap);
                    if (null == goodsPo) {
                        throw new GlobalException(new ResponseException(400, "商品不存在或已下架"));
                    }
                    if (goodsPo.getIsDelete() == 1 || goodsPo.getGoodsStatus() != 1) {
//                            errorMsg = "商品不存在或已下架";
                        throw new GlobalException(new ResponseException(400, "商品不存在或已下架"));
                    }
                    paramsMap.put("skuKey", goodsPo.getSkuKey());
                    if (goodsPo.getGoodsCount() < goodsNum) {
//                            errorMsg = "商品库存不足";
                        throw new GlobalException(new ResponseException(400, "商品库存不足"));
                    }
                    Integer updateCount = 0;
                    if (skuId == null) {//设置SKU
                        updateCount = mallDao.updateGoodsCount(paramsMap);
                    } else {//未设置
                        mallDao.updateGoodsCount(paramsMap);
                        updateCount = mallDao.updateGoodsSkuCount(paramsMap);
                    }
                    if (updateCount == 0) {//更新库存失败
//                            errorMsg = "商品库存不足";
                        throw new GlobalException(new ResponseException(400, "商品库存不足"));
                    } else {//下单成功，创建支付订单
                        cutTag = true;
                    }
                    //生成订单信息
                    MerchantOrderPo orderPo = new MerchantOrderPo();
                    orderPo.setChargeType(2);//微信支付
                    orderPo.setCustomerId(customerId);
                    orderPo.setOrderSn(orderSn);
                    orderPo.setAddressId(addressId);
                    orderPo.setGoodsAmountCent(goodsPo.getAmountCent() * goodsNum);
                    orderPo.setGoodsNum(goodsNum);
                    orderPo.setPaymentState(0);
                    orderPo.setOrderAmountCent(goodsPo.getAmountCent() * goodsNum + goodsPo.getGoodsFreightCent());
                    orderPo.setOrderTotalPriceCent(goodsPo.getAmountCent() * goodsNum + goodsPo.getGoodsFreightCent());
                    orderPo.setShippingFeeCent(goodsPo.getGoodsFreightCent());
                    orderPo.setOrderState(10);
                    orderPo.setOrgId(orgId);
                    orderPo.setOrderType(2);
                    orderPo.setAreaName(orderAddressDto.getAreaName());
                    orderPo.setCityName(orderAddressDto.getCityName());
                    orderPo.setProvinceName(orderAddressDto.getProvinceName());
                    orderPo.setDetailedAddress(orderAddressDto.getAddressInfo());
                    orderPo.setPhone(orderAddressDto.getPhone());
                    orderPo.setRealName(orderAddressDto.getRealName());
                    orderPo.setPaySn(paySn);
                    if (!StringUtils.isEmpty(distributor)) {
                        orderPo.setSalerId(distributor);
                    }
                    mallDao.insertMerchantOrderInfo(orderPo);
                    totalFee = orderPo.getOrderAmountCent();
                    List<MerchantOrderGoodsPo> orderGoodsPoList = new ArrayList<>();
                    MerchantOrderGoodsPo orderGoodsPo = new MerchantOrderGoodsPo();
                    orderGoodsPo.setOrderId(orderPo.getOrderId());
                    orderGoodsPo.setAmountCent(goodsPo.getAmountCent());
                    orderGoodsPo.setCustomerId(customerId);
                    orderGoodsPo.setBuyCount(goodsNum);
                    orderGoodsPo.setGoodsId(goodsPo.getGoodsId());
                    orderGoodsPo.setGoodsCover(goodsPo.getGoodsCover());
                    orderGoodsPo.setGoodsName(goodsPo.getGoodsName());
                    orderGoodsPo.setGoodsPayPriceCent(goodsPo.getAmountCent());
                    orderGoodsPo.setSkuId(goodsPo.getSkuId());
                    orderGoodsPo.setSkuKey(goodsPo.getSkuKey());
                    orderGoodsPo.setSkuValue(goodsPo.getSkuValue());
                    orderGoodsPo.setStatus(0);
                    orderGoodsPoList.add(orderGoodsPo);
                    //填装商品
                    orderPo.setOrderGoods(orderGoodsPoList);
                    orderPos.add(orderPo);
                    mallDao.insertMerchantOrderGoods(orderGoodsPoList);

                    // 添加记录
                    Map<String, Object> map = new HashMap<>();
                    map.put("objectId", orderSn);
                    map.put("customerId", customerId);
                    map.put("orgId", orgId);
                    this.addToDealData(map, 3);

                } else if (shoppingCartIds != null) {//购物车下单
                    paySn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
                    List<ShoppingCartPo> shoppingCartPos = mallDao.getShoppingCartByIds(paramsMap);
                    for (ShoppingCartPo cartPo : shoppingCartPos) {//购物车按商户分类，不同商户生成不同订单记录，支付订单号相同
                        orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
                        Long goodAmount = 0L;
                        Long orderAmount = 0L;
                        Long orderTotalPrice = 0L;
                        Long goodsFreight = 0L;
                        Integer goodsBuyNum = 0;
                        List<MerchantOrderGoodsPo> orderGoodsPoList = new ArrayList<>();
                        for (ShoppingCartGoodsPo goodsPo : cartPo.getGoodsList()) {
                            MerchantOrderGoodsPo orderGoodsPo = new MerchantOrderGoodsPo();
                            if (goodsPo.getIsDelete() == 1 || goodsPo.getGoodsStatus() != 1) {
//                                    errorMsg = "部分商品不存在或已下架";
                                throw new GlobalException(new ResponseException(400, goodsPo.getGoodsName() + "不存在或已下架"));
                            }
                            if (goodsPo.getGoodsCount() < goodsPo.getBuyCount()) {
//                                    errorMsg = "部分商品库存不足";
                                throw new GlobalException(new ResponseException(400, goodsPo.getGoodsName() + "库存不足"));
                            }
                            Integer updateCount = 0;
                            goodsBuyNum = goodsBuyNum + goodsPo.getBuyCount();
                            paramsMap.put("goodsId", goodsPo.getGoodsId());
                            paramsMap.put("skuKey", goodsPo.getSkuKey());
                            paramsMap.put("goodsNum", goodsPo.getBuyCount());
                            if (goodsPo.getSkuId() == null) {//设置SKU
                                updateCount = mallDao.updateGoodsCount(paramsMap);
                            } else {//未设置
                                mallDao.updateGoodsCount(paramsMap);
                                updateCount = mallDao.updateGoodsSkuCount(paramsMap);
                            }
                            if (updateCount == 0) {//更新库存失败
//                                    errorMsg = "部分商品库存不足";
                                throw new GlobalException(new ResponseException(400, goodsPo.getGoodsName() + "库存不足"));
                            } else {
                                goodAmount += goodsPo.getBuyCount() * goodsPo.getAmountCent();
                                orderAmount += goodsPo.getBuyCount() * goodsPo.getAmountCent();
                                orderTotalPrice = orderAmount;
                                if (goodsPo.getGoodsFreightCent() > goodsFreight) {//取运费最大
                                    goodsFreight = goodsPo.getGoodsFreightCent();
                                }
                                orderGoodsPo.setAmountCent(goodsPo.getAmountCent());
                                orderGoodsPo.setCustomerId(customerId);
                                orderGoodsPo.setBuyCount(goodsPo.getBuyCount());
                                orderGoodsPo.setGoodsId(goodsPo.getGoodsId());
                                orderGoodsPo.setGoodsCover(goodsPo.getGoodsCover());
                                orderGoodsPo.setGoodsName(goodsPo.getGoodsName());
                                orderGoodsPo.setGoodsPayPriceCent(goodsPo.getAmountCent());
                                orderGoodsPo.setSkuId(goodsPo.getSkuId());
                                orderGoodsPo.setSkuKey(goodsPo.getSkuKey());
                                orderGoodsPo.setSkuValue(goodsPo.getSkuValue());
                                orderGoodsPo.setStatus(0);
                                orderGoodsPoList.add(orderGoodsPo);
                            }
                        }
                        orderAmount = orderAmount + goodsFreight;
                        orderTotalPrice = orderTotalPrice + goodsFreight;
                        //生成订单信息
                        MerchantOrderPo orderPo = new MerchantOrderPo();
                        orderPo.setChargeType(2);//微信支付
                        orderPo.setCustomerId(customerId);
                        orderPo.setOrderSn(orderSn);
                        orderPo.setAddressId(addressId);
                        orderPo.setGoodsAmountCent(goodAmount);
                        orderPo.setGoodsNum(goodsBuyNum);
                        orderPo.setPaymentState(0);
                        orderPo.setOrderAmountCent(orderAmount);
                        orderPo.setOrderTotalPriceCent(orderTotalPrice);
                        orderPo.setShippingFeeCent(goodsFreight);
                        orderPo.setOrderState(10);//待付款
                        orderPo.setMerchantId(cartPo.getMerchantId());
                        orderPo.setOrderType(2);//
                        orderPo.setAreaName(orderAddressDto.getAreaName());
                        orderPo.setCityName(orderAddressDto.getCityName());
                        orderPo.setProvinceName(orderAddressDto.getProvinceName());
                        orderPo.setDetailedAddress(orderAddressDto.getAddressInfo());
                        orderPo.setPhone(orderAddressDto.getPhone());
                        orderPo.setRealName(orderAddressDto.getRealName());
                        orderPo.setOrgId(orgId);
                        orderPo.setPaySn(paySn);
                        mallDao.insertMerchantOrderInfo(orderPo);
                        totalFee = totalFee + orderAmount;
                        for (MerchantOrderGoodsPo goodsPo : orderGoodsPoList) {
                            goodsPo.setOrderId(orderPo.getOrderId());
                        }
                        //填装商品
                        orderPo.setOrderGoods(orderGoodsPoList);
                        orderPos.add(orderPo);
                        mallDao.insertMerchantOrderGoods(orderGoodsPoList);
                    }

                    // 添加记录
                    Map<String, Object> map = new HashMap<>();
                    map.put("objectId", paySn);
                    map.put("customerId", customerId);
                    map.put("orgId", orgId);
                    this.addToDealData(map, 3);

                } else if (payTradeId != null) {//支付未支付订单
                    orderSn = payTradeId;
                    List<MerchantOrderPo> orderList = mallDao.getMerchantOrderByPayTradeId(orderSn);
                    for (MerchantOrderPo orderPo : orderList) {
                        orderPos.add(orderPo);
                        totalFee = totalFee + orderPo.getOrderAmountCent();
                    }
                }
                //0元商品
                if (0 == totalFee) {
                    Map<String, String> ordtmpparams = new HashMap<>();
                    ordtmpparams.put("wxpayId", paySn);
                    ordtmpparams.put("wxtransactionId", "");
                    ordtmpparams.put("status", "1");
                    mallDao.updateMerchantOrderInfo(ordtmpparams);
                    mallDao.updateMerchantOrderGoodsInfo(ordtmpparams);

                    HashMap<String, Object> outTradeNoInfo = mallDao.getOrderByPayTradeId(paySn);
                    List<Map<String, Object>> orderGoodsList = mallDao.getOrderGoodsByOrderId(Integer.parseInt(outTradeNoInfo.get("orderId").toString()));
                    for (Map<String, Object> og : orderGoodsList) {
                        if (og != null) {
                            Map<String, Object> ogParams = new HashMap<>();
                            ogParams.put("buyCount", Integer.parseInt(og.get("goodsNum").toString()));
                            ogParams.put("goodsId", Integer.parseInt(og.get("goodsId").toString()));
                            mallDao.editGoodSalesNum(ogParams);
                        }
                    }

                    lettuceLock.releaseLock(lockKey, requestId);
                    Map<String, String> retData = new HashMap<>();
                    retData.put("status", "1");
                    retData.put("tip", "0元商品购买成功");
                    retData.put("orderSn", paySn);
                    return retData;
                }


                Long currentTime = new Date().getTime();
                Map<String, String> params = new HashMap<>();
                params.put("body", "step商城订单");
                params.put("notifyUrl", notifyUrl);
                params.put("openid", openId);
                params.put("outTradeNo", paySn);
                params.put("timestamp", currentTime.toString());
                params.put("totalFee", totalFee.toString());
                params.put("tradeType", "JSAPI");
                params.put("wcpayType", wxpayType);
                Map<String, String> appSign = ParamSignUtils.sign(params);
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                nvps.add(new BasicNameValuePair("appSign", appSign.get("appSign")));
                nvps.add(new BasicNameValuePair("notifyUrl", params.get("notifyUrl")));
                nvps.add(new BasicNameValuePair("body", params.get("body")));
                nvps.add(new BasicNameValuePair("outTradeNo", params.get("outTradeNo")));
                nvps.add(new BasicNameValuePair("openid", params.get("openid")));
                nvps.add(new BasicNameValuePair("timestamp", params.get("timestamp")));
                nvps.add(new BasicNameValuePair("totalFee", params.get("totalFee")));
                nvps.add(new BasicNameValuePair("tradeType", params.get("tradeType")));
                nvps.add(new BasicNameValuePair("wcpayType", params.get("wcpayType")));
                String result = null;
                if (redisTemplate.opsForValue().get(paySn) == null) {
                    result = ParamSignUtils.callService(payurl + "/pay/wcpay", nvps, 0, 0);
                    redisTemplate.opsForValue().set(paySn, result);
                } else {
                    result = redisTemplate.opsForValue().get(paySn);
                }
                Object parse = JSON.parse(result);
                Map ret = (Map) parse;

                if ((Integer) ret.get("rt") != 1) {
                    try {
                        for (MerchantOrderPo order : orderPos) {
                            for (MerchantOrderGoodsPo goods : order.getOrderGoods()) {
                                Map<String, Object> paramsa = new HashMap<>();
                                //恢复库存
                                paramsa.put("goodsId", goods.getGoodsId());
                                paramsa.put("skuKey", goods.getSkuKey());
                                paramsa.put("goodsNum", goods.getBuyCount());
                                if (goods.getSkuKey() == null) {//设置SKU
                                    mallDao.addGoodsCount(paramsa);
                                } else {//未设置
                                    mallDao.addGoodsCount(paramsa);
                                    mallDao.addGoodsSkuCount(paramsa);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Map<String, String> oretData = new HashMap<>();
                    oretData.put("status", "-1");
                    oretData.put("tip", "微信签名失败");
                    oretData.put("orderSn", paySn);
                    return oretData;
//                        throw new GlobalException(new ResponseException(400, "微信签名失败"));
                } else {
                    Map retInfo = (Map) ret.get("object");
                    if (shoppingCartIds != null) {
                        for (String shoppingCartId : shoppingCartIds) {
                            mallDao.deleteShoppingCartById(Long.parseLong(shoppingCartId));
                        }
                    }
                    finalpackage.put("appId", retInfo.get("appId"));
                    finalpackage.put("timeStamp", retInfo.get("timeStamp"));
                    finalpackage.put("nonceStr", retInfo.get("nonceStr"));
                    finalpackage.put("package", "prepay_id=" + retInfo.get("prepayId"));
                    finalpackage.put("signType", retInfo.get("signType"));
                    finalpackage.put("paySign", retInfo.get("paySign"));
                    finalpackage.put("orderSn", paySn);
                    lettuceLock.releaseLock(lockKey, requestId);
                    if (payTradeId == null) {//待支付订单不重新创建超时关闭任务
                        TimerContext context = new TimerContext(3600, 1);
                        TimerScheduler scheduler = new TimerScheduler(context);
                        final List<MerchantOrderPo> orderInfos = orderPos;
                        scheduler.addTask(new Runnable() {
                            public void run() {
                                try {
                                    for (MerchantOrderPo order : orderInfos) {
                                        Integer result = mallDao.closeMerchantOrderInfo(order.getOrderId());
                                        if (result > 0) {
                                            for (MerchantOrderGoodsPo goods : order.getOrderGoods()) {
                                                Map<String, Object> params = new HashMap<>();
                                                //恢复库存
                                                params.put("goodsId", goods.getGoodsId());
                                                params.put("skuKey", goods.getSkuKey());
                                                params.put("goodsNum", goods.getBuyCount());
                                                if (goods.getSkuKey() == null) {//未设置SKU
                                                    Integer ifSku = mallDao.getIfGoodsSetSku(params);
                                                    if (ifSku == 0) {
                                                        mallDao.addGoodsCount(params);
                                                    }
                                                } else {//设置
                                                    Integer rt = mallDao.addGoodsSkuCount(params);
                                                    if (rt > 0) {
                                                        mallDao.addGoodsCount(params);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }, 3600);
                        Timer timer = new Timer();
                        timer.scheduleAtFixedRate(scheduler, 0, context.getTickDuration() * 1000L);
                    }
                }
            } else {
                throw GlobalException.build("暂不支持其他支付方式");
            }
        } else {
            throw GlobalException.build("正在帮您处理,请勿重新提交!");
        }
        lettuceLock.releaseLock(lockKey, requestId);
        return finalpackage;
    }

    /**
     * @Description:添加到DaelData表
     * @Param: customerId
     * @Param: orgId
     * @Param: objectId
     * @Param: actionType 2-点击3-创建4-支付5-完成
     * @Return:
     * @Author: wuyue
     * @Date: 2019/9/5 13:24
     * @Version: v1.8.3
     */
    public void addToDealData(Map<String, Object> map, int actionType) {
        // 开启状态
        Integer status = mallDao.getRobotStatusByOrgId((String) map.get("orgId"));
        if (status == null || status != 1) {
            // 未开启
            return;
        }
        switch (actionType) {
            case 2:
                // 判断该用户是不是第一次点击该商品
                Integer integer = mallDao.judgeFirstTimeByCidOidAndType(map);
                if (integer != 0) {
                    return;
                }
                // 通过商品id查找文章id
                List<String> newsId = mallDao.getArticleIdByGoodsId((Long) map.get("objectId"));
                if (newsId == null || newsId.size() == 0) {
                    return;
                }
                map.put("newsId", newsId);
                // 判断文章是否为24小时内发送给该用户的
                Integer integer1 = mallDao.judgeArticleSendWithinOneDayByNewsId(map);
                if (integer1 == 0) {
                    return;
                }
                break;
            case 3:
            case 4:
            case 5:
                // 判断订单中商品是否在营销文库中，且文章是否为24小时内发送给该用户
                // sn->newsId
                String orderSn = (String) map.get("objectId");
                List<String> articleId = mallDao.getArticleIdByOrderSn(orderSn);
                if (articleId == null || articleId.size() == 0) {
                    return;
                }
                map.put("newsId", articleId);
                Integer integer2 = mallDao.judgeArticleSendWithinOneDayByNewsId(map);
                if (integer2 == 0) {
                    return;
                }
                break;
            default:
                return;
        }
        map.put("actionType", actionType);
        // 插入记录
        mallDao.addToDealData(map);
    }

    public void orderNotify(Map<String, Object> paraMap) {
//        System.out.println("==============微信支付回调test==============");
//        System.out.println(paraMap.toString());
        int chargeStatus = 0;
        if (!StringUtils.isEmpty(paraMap.get("transactionId"))) {
            chargeStatus = 1;
        }
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("wxpayId", (String) paraMap.get("outTradeNo"));
        paramsMap.put("status", String.valueOf(chargeStatus));
        paramsMap.put("wxtransactionId", (String) paraMap.get("transactionId"));
        mallDao.updateMerchantOrderInfo(paramsMap);
        mallDao.updateMerchantOrderGoodsInfo(paramsMap);

        SimpleDateFormat utime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HashMap<String, Object> outTradeNoInfo = mallDao.getOrderByPayTradeId((String) paraMap.get("outTradeNo"));
        Map<String, Object> tradeParams = new HashMap<>();
        tradeParams.put("tradeType", "4");
        tradeParams.put("tradeOrderNum", paraMap.get("transactionId"));
        tradeParams.put("payInfo", paraMap.get("outTradeNo"));
        tradeParams.put("moneyType", "RMB");
        tradeParams.put("tradeSum", outTradeNoInfo.get("orderTotalPrice"));
        tradeParams.put("sumRMB", outTradeNoInfo.get("orderTotalPrice"));
        tradeParams.put("chargeType", "2");
        tradeParams.put("orgId", outTradeNoInfo.get("orgId").toString());
        tradeParams.put("payUser", outTradeNoInfo.get("customerId").toString());
        tradeParams.put("tradeTime", utime.format(new Date()));
        mallDao.addPayTrade(tradeParams);

        List<Map<String, Object>> orderGoodsList = mallDao.getOrderGoodsByOrderId(Integer.parseInt(outTradeNoInfo.get("orderId").toString()));
        for (Map<String, Object> og : orderGoodsList) {
            if (og != null) {
                Map<String, Object> ogParams = new HashMap<>();
                ogParams.put("buyCount", Integer.parseInt(og.get("goodsNum").toString()));
                ogParams.put("goodsId", Integer.parseInt(og.get("goodsId").toString()));
                mallDao.editGoodSalesNum(ogParams);
            }
        }
    }

    public Object getOrderList(Map<String, Object> params) {
        Integer payMode = this.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        List<MerchantOrderPo> goodsPoList = new ArrayList<>();
        Integer pageIndex = (Integer) params.get("pageIndex");
        if (StringUtils.isEmpty(pageIndex) || pageIndex < 1) {
            pageIndex = 1;
        }
        int perPage = 20;
        int count = mallDao.getUserOrderCount(params);
        if (count > 0) {
            PageHelper.startPage(pageIndex, perPage);
            goodsPoList = mallDao.getUserOrderList(params);
            for (MerchantOrderPo orderPo : goodsPoList) {
                orderPo.setRefundAmount(NumberUtils.fenToYuan(Long.valueOf(orderPo.getRefundAmount())));
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTime(orderPo.getCreateTime());
//                calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 60);// 让日期加1
//                if (orderPo.getOrderState() == 10 && calendar.getTime().before(new Date())) {//订单超时自动关闭
//                    orderPo.setOrderState(0);
//                }
                Integer isMallBoomOrder = 1;
                Integer goodsNum = 0;
                Long orderId = orderPo.getOrderId();
                params.put("orderId", orderId);
                String orderSn = orderPo.getOrderSn();
                List<MerchantOrderGoodsPo> list;
                if (orderSn.startsWith("I")) {
                    list = mallDao.getIntegralOrderGoodsList(orderId);
                } else {
                    list = mallDao.getMerchantOrderGoodsList(params);
                }

                orderPo.setOrderGoods(list);
                for (MerchantOrderGoodsPo orderGoodsPo : list) {
                    goodsNum = goodsNum + orderGoodsPo.getBuyCount();
                    if (!StringUtils.isEmpty(orderGoodsPo.getBelongId())) {
                        isMallBoomOrder = 0;
                    }
                }
                orderPo.setGoodsNum(goodsNum);
                orderPo.setType(isMallBoomOrder);
            }
        }
        return new PageInfo<>(goodsPoList);
    }

    public Object getSalerOrderList(Map<String, Object> params) {
        Integer payMode = this.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        List<MerchantOrderPo> goodsPoList = new ArrayList<>();
        Integer pageIndex = (Integer) params.get("pageIndex");
        if (StringUtils.isEmpty(pageIndex) || pageIndex < 1) {
            pageIndex = 1;
        }
        int perPage = 20;
        int count = mallDao.getSalerOrderCount(params);
        if (count > 0) {
            PageHelper.startPage(pageIndex, perPage);
            goodsPoList = mallDao.getSalerOrderList(params);
            for (MerchantOrderPo orderPo : goodsPoList) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(orderPo.getCreateTime());
                calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 60);// 让日期加1
                if (orderPo.getOrderState() == 10 && calendar.getTime().before(new Date())) {//订单超时自动关闭
                    orderPo.setOrderState(0);
                }
                Integer goodsNum = 0;
                Long orderId = orderPo.getOrderId();
                params.put("orderId", orderId);
                List<MerchantOrderGoodsPo> list = mallDao.getMerchantOrderGoodsList(params);
                orderPo.setOrderGoods(list);
                for (MerchantOrderGoodsPo orderGoodsPo : list) {
                    goodsNum = goodsNum + orderGoodsPo.getBuyCount();
                }
                orderPo.setGoodsNum(goodsNum);
            }
        }
        return new PageInfo<>(goodsPoList);
    }

    public Object getOrderInfo(Map<String, Object> params) throws GlobalException, ParseException {
        Calendar calendar = Calendar.getInstance();
        Integer payMode = this.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        MerchantOrderPo orderPo = mallDao.getUserOrderInfoById(params);
        if (orderPo == null) {
            throw GlobalException.build("订单不存在或已被删除");
        }
        if(orderPo.getIsVirtual()==1){
            orderPo.setAddressId(null);
            orderPo.setAddressInfo(null);
        }
        //供货订单
        if (!StringUtils.isEmpty(orderPo.getMallsGoodsId())) {
            Map mallsGoodsInfo = goodsService.getGoodsInfo(orderPo.getMallsGoodsId().toString());
            orderPo.setMallsBelongId(mallsGoodsInfo.get("belongId").toString());
            orderPo.setMallsOrgId(mallsGoodsInfo.get("orgId").toString());
        }

        String isEnd1 = mallDao.getIfEnd(params);
        if (null == isEnd1) {
            isEnd1 = "2";
        }
        orderPo.setIsEnd(Integer.valueOf(isEnd1));
        orderPo.setRefundAmount(NumberUtils.fenToYuan(Long.valueOf(orderPo.getRefundAmount())));
        params.put("orderId", orderPo.getOrderId());
        List<MerchantOrderGoodsPo> goodsPos = mallDao.getMerchantOrderGoodsList(params);
//        StringBuilder shippingCode = new StringBuilder();
//        StringBuilder expressName = new StringBuilder();
        String shippingCode = "";
        String expressName = "";
        Integer shippingType = 0;
        calendar.setTime(orderPo.getCreateTime());
        calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 60);// 让日期加1
        orderPo.setPayEndTime(calendar.getTime());
        if (orderPo.getOrderState() == 10 && calendar.getTime().getTime() <= new Date().getTime()) {//订单超时自动关闭
            orderPo.setOrderState(0);
        }
        Integer goodsNum = 0;
        orderPo.setType(1);
        List<Map<String, Object>> shippingList = new ArrayList<>();
        for (MerchantOrderGoodsPo po : goodsPos) {
            if (po.getShippingCode() != null) {
                //取所有包裹的物流信息
                shippingCode = po.getShippingCode();
                expressName = po.getExpressName();
                Map<String, Object> expressList = commonsService.getExpressList(shippingCode);
                if ("0".equals(expressList.get("status"))) {
                    Map<String, Object> shippingMap = new HashMap<>();
                    shippingMap.put("shippingCode", shippingCode);
                    Map<String, Object> da = (Map) commonsService.getExpressList(shippingCode).get("result");
                    long time = 0L;
                    if (!StringUtils.isEmpty(da.get("updateTime"))) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = simpleDateFormat.parse(da.get("updateTime").toString());
                        time = date.getTime();
                    }
                    shippingMap.put("expressUpdateTime", (int) time);
                    shippingList.add(shippingMap);
                }
            }
            if (po.getShippingType() == 1) {
                shippingType = 1;
            }
            po.setShippingFeeString(NumberUtils.fenToYuan(Long.valueOf(po.getShippingFee().toString())));
            goodsNum = goodsNum + po.getBuyCount();
            Long goodsId = po.getGoodsId();
            String belongId = mallBoomDao.getBelongIdByGoodsId(goodsId);
            if (!StringUtils.isEmpty(belongId)) {
                orderPo.setType(0);
            }
            Long goodsTotalFee = po.getGoodsPayPriceCent() * po.getGoodsNum() + po.getShippingFee();
            po.setGoodsTotalFee(NumberUtils.fenToYuan(goodsTotalFee));
            //返回对应商品的商户id
            Map<String, Object> storeMap = mallDao.getMerchantIdByGoodsId(goodsId.toString());
            Long merchantId = null;
            if (null != storeMap.get("merchantId")) {
                merchantId = Long.valueOf(storeMap.get("merchantId").toString());
            }
            po.setMerchantId(merchantId);
        }
        if (shippingList.size() > 0) {
            shippingList.sort((o1, o2) -> {
                Integer name1 = Integer.valueOf(o1.get("expressUpdateTime").toString());
                Integer name2 = Integer.valueOf(o2.get("expressUpdateTime").toString());
                return name2.compareTo(name1);
            });
            shippingCode = shippingList.get(0).get("shippingCode").toString();
        }

        orderPo.setOrderGoods(goodsPos);
        orderPo.setGoodsNum(goodsNum);
        orderPo.setShippingCode(shippingCode);
        orderPo.setExpressName(expressName);
        orderPo.setShippingType(shippingType);
        if (!StringUtils.isEmpty(orderPo.getIntegralPaymentAmount())) {
            orderPo.setPayScoreStr(NumberUtils.fenToYuan(orderPo.getIntegralPaymentAmount().longValue()));
        } else {
            orderPo.setPayScoreStr("0.00");
        }
        return orderPo;
    }

    public MerchantOrderPo getIntegralOrderInfo(String orderSn) throws GlobalException, ParseException {
        Calendar calendar = Calendar.getInstance();
        MerchantOrderPo orderPo = mallDao.getUserIntegralOrderInfoBySn(orderSn);
        if (orderPo == null) {
            throw GlobalException.build("订单不存在或已被删除");
        }
        orderPo.setIsEnd(1);
        orderPo.setRefundAmount(NumberUtils.fenToYuan(Long.valueOf(orderPo.getRefundAmount())));
        List<MerchantOrderGoodsPo> goodsPos = mallDao.getIntegralOrderGoodsList(orderPo.getOrderId());
        String shippingCode = "";
        String expressName = "";
        int shippingType = 0;
        calendar.setTime(orderPo.getCreateTime());
        calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 60);// 让日期加1
        orderPo.setPayEndTime(calendar.getTime());
        if (orderPo.getOrderState() == 10 && calendar.getTime().getTime() <= new Date().getTime()) {//订单超时自动关闭
            orderPo.setOrderState(0);
        }
        Integer goodsNum = 0;
        orderPo.setType(1);
        List<Map<String, Object>> shippingList = new ArrayList<>();
        for (MerchantOrderGoodsPo po : goodsPos) {
            if (po.getShippingCode() != null) {
                //取所有包裹的物流信息
                shippingCode = po.getShippingCode();
                expressName = po.getExpressName();
                Map<String, Object> expressList = commonsService.getExpressList(shippingCode);
                if ("0".equals(expressList.get("status"))) {
                    Map<String, Object> shippingMap = new HashMap<>();
                    shippingMap.put("shippingCode", shippingCode);
                    Map<String, Object> da = (Map) commonsService.getExpressList(shippingCode).get("result");
                    long time = 0L;
                    if (!StringUtils.isEmpty(da.get("updateTime"))) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = simpleDateFormat.parse(da.get("updateTime").toString());
                        time = date.getTime();
                    }
                    shippingMap.put("expressUpdateTime", (int) time);
                    shippingList.add(shippingMap);
                }
            }
            if (po.getShippingType() == 1) {
                shippingType = 1;
            }
            po.setShippingFeeString(NumberUtils.fenToYuan(Long.valueOf(po.getShippingFee().toString())));
            goodsNum = goodsNum + po.getBuyCount();
            Long goodsId = po.getGoodsId();
            String belongId = mallBoomDao.getBelongIdByGoodsId(goodsId);
            if (!StringUtils.isEmpty(belongId)) {
                orderPo.setType(0);
            }
            Long goodsTotalFee = po.getGoodsPayPriceCent() * po.getGoodsNum() + po.getShippingFee();
            po.setGoodsTotalFee(NumberUtils.fenToYuan(goodsTotalFee));
        }
        if (shippingList.size() > 0) {
            shippingList.sort((o1, o2) -> {
                Integer name1 = Integer.valueOf(o1.get("expressUpdateTime").toString());
                Integer name2 = Integer.valueOf(o2.get("expressUpdateTime").toString());
                return name2.compareTo(name1);
            });
            shippingCode = shippingList.get(0).get("shippingCode").toString();
        }

        orderPo.setOrderGoods(goodsPos);
        orderPo.setGoodsNum(goodsNum);
        orderPo.setShippingCode(shippingCode);
        orderPo.setExpressName(expressName);
        orderPo.setShippingType(shippingType);
        if (!StringUtils.isEmpty(orderPo.getIntegralPaymentAmount())) {
            orderPo.setPayScoreStr(NumberUtils.fenToYuan(orderPo.getIntegralPaymentAmount().longValue()));
        } else {
            orderPo.setPayScoreStr("0.00");
        }
        return orderPo;
    }

    public void delShoppingOrder(Map<String, Object> params) {
        Integer payMode = this.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        mallDao.delShoppingOrder(params);
    }

    public void delIntegralShoppingOrder(Map<String, Object> params) {
        Integer payMode = this.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        mallDao.delIntegralShoppingOrder(params);
    }

    public void cancelShoppingOrder(Map<String, Object> params) throws GlobalException {
        Integer payMode = this.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        Integer i = mallDao.checkOrderIfCancel(params);
        if (i != 0) {
            throw GlobalException.build("订单已取消");
        }
        String orderSn = "";
        if (!StringUtils.isEmpty(params.get("orderId"))) {
            orderSn = integralH5Dao.getAllOrderSnByOrderId(Long.valueOf(params.get("orderId").toString()));
        }
        if (!StringUtils.isEmpty(orderSn) && orderSn.startsWith("I")) {
            Long orderId = Long.valueOf(params.get("orderId").toString());
            integralH5Service.cancelShoppingOrder(orderId);
            return;
        } else {
            mallDao.cancelShoppingOrder(params);
            List<MerchantOrderGoodsPo> goodsPos = mallDao.getMerchantOrderGoodsList(params);
            for (MerchantOrderGoodsPo po : goodsPos) {
                //恢复库存
                params.put("goodsId", po.getGoodsId());
                params.put("skuKey", po.getSkuKey());
                params.put("goodsNum", po.getBuyCount());

                if (po.getSkuId() == null) {
                    this.rollBackMallsGoodsCount(po.getGoodsId(), null, po.getBuyCount(), po.getMallsGoodsId());
//                Integer ifSku = mallDao.getIfGoodsSetSku(params);
//                if (ifSku == 0) {
//                    this.flushGoodsCache(false,po.getGoodsId(),null,po.getBuyCount().longValue());
//                    mallDao.addGoodsCount(params);
//                }
                } else {//设置
//                int rt = mallDao.addGoodsSkuCount(params);
                    Long skuId = mallDao.getSkuIdByGoodsIdAndSkuKey(params);
                    this.rollBackMallsGoodsCount(po.getGoodsId(), skuId.toString(), po.getBuyCount(), po.getMallsGoodsId());
//                this.flushGoodsCache(false,po.getGoodsId(),skuId.toString(),po.getBuyCount().longValue());
//                if (rt > 0) {
//                    mallDao.addGoodsCount(params);
//                    this.flushGoodsCache(false,po.getGoodsId(),null,po.getBuyCount().longValue());
//                }
                }
            }
            //订单是否有积分抵扣
            Map orderInfo = mallBoomDao.getOrderInfoById(Long.valueOf(params.get("orderId").toString()), 1);
            Long score = Long.valueOf(orderInfo.get("score").toString());
            if (score > 0) {
                params.put("score", score);
                // 恢复积分
                params.put("customerId", orderInfo.get("customerId"));
                mallDao.recoveryScoreById(params);
                //记录金币变动记录
                Map<String, Object> scoreLog = new HashMap<>();
                scoreLog.put("customerId", orderInfo.get("customerId"));
                scoreLog.put("score", score);
                scoreLog.put("type", 2);
                scoreLog.put("orderSn", orderInfo.get("orderSn"));
                purchaseProcessDao.addScoreLog(scoreLog);
                try {
                    String orderId = params.get("orderId").toString();
                    //根据id查出orderSn，paySn，payMode
                    OrderScore orderScore = mallDao.getOrderScore(orderId);
                    if (orderScore != null) {
                        String balanceSplitItemsString = stringRedisTemplate.opsForValue().get(PurchaseProcessNewServiceImpl.CANCEL_SCORE_ORDER + orderScore.getOrderSn());
                        List<Map> balanceSplitItems = com.alibaba.fastjson.JSON.parseArray(balanceSplitItemsString, Map.class);
                        Integer balanceAmount = 0;
                        if (balanceSplitItems != null && balanceSplitItems.size() > 0) {
                            for (Map<String, Object> balanceSplitItemA : balanceSplitItems) {
                                Integer amount = 0;
                                if (!StringUtils.isEmpty(balanceSplitItemA.get("amount"))) {
                                    amount = (Integer) balanceSplitItemA.get("amount");
                                }
                                balanceAmount = balanceAmount + amount;
                            }
                        }
                        List<Map<String, Object>> cashSplitItems = new ArrayList<>();
                        String cashSplitItemsString = com.alibaba.fastjson.JSON.toJSONString(cashSplitItems);
                        if (balanceAmount > 0) {
                            ledgerProcessService.refund(orderScore.getOrderSn(), balanceAmount.toString(), balanceSplitItemsString, "0", cashSplitItemsString, orderScore.getPaySn(), orderScore.getPayMode());
                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String consumptionId = (String) orderInfo.get("consumptionId");
            String couponId = (String) orderInfo.get("couponId");
            if (!StringUtils.isEmpty(consumptionId) && !StringUtils.isEmpty(couponId)) {
                CouponCustomerInfo couponCustomerInfo = (CouponCustomerInfo) params.get("couponCustomerInfo");
                //使用优惠券回滚
                couponH5Service.useConsumption(consumptionId, null, orderInfo.get("orderSn").toString(), null, null, 1, couponCustomerInfo);
            }
            Long orderId = Long.valueOf(params.get("orderId").toString());
            // 恢复赠品
            purchaseProcessDao.recoveryExerciseByOrderId(orderId);
            // 删除赠品记录
            purchaseProcessDao.deleteExerciseRecordByOrderId(orderId);
        }
    }


    //供货商商品加库存
    public void rollBackMallsGoodsCount(Long goodsId, String skuId, Integer goodsNum, Long mallsGoodsId) {
        Map<String, Object> mapM = new HashMap<>();
        mapM.put("goodsNum", goodsNum);
        Long goodsIdGoods = goodsId;
        if (!StringUtils.isEmpty(mallsGoodsId)) {
            goodsIdGoods = mallsGoodsId;
        }
        mapM.put("goodsId", goodsIdGoods);
        mallDao.addMallGoodsCount(mapM);
        this.flushGoodsCache(false, goodsIdGoods, null, goodsNum.longValue());

        if (!StringUtils.isEmpty(skuId)) {
            Map<String, Object> skuInfo = mallDao.getSkuById(skuId);
            if (!StringUtils.isEmpty(skuInfo.get("mallsSkuId"))) {
                skuId = skuInfo.get("mallsSkuId").toString();
                goodsId = mallsGoodsId;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("skuId", skuId);
            map.put("goodsNum", goodsNum);
            purchaseProcessDao.addMallGoodsSkuCount(map);
            this.flushGoodsCache(false, goodsId, skuId, goodsNum.longValue());
        }

//        mallDao.addGoodsCount(mapM);
//        if(!StringUtils.isEmpty(mallsGoodsId)){
//            List<Map<String, Object>> mallsGoodsList = mallDao.getMallsGoodsList(mallsGoodsId,goodsId);
//            for (Map<String, Object> da : mallsGoodsList) {
//                Map<String, Object> mapM2 = new HashMap<>();
//                mapM2.put("goodsId", da.get("goodsId"));
//                mapM2.put("goodsNum", goodsNum);
//                mallDao.addGoodsCount(mapM2);
//            }
//            this.flushGoodsCache(false,mallsGoodsId,null,goodsNum.longValue());
//        }else {
//            this.flushGoodsCache(false,goodsId,null,goodsNum.longValue());
//        }

//        if (!StringUtils.isEmpty(skuId)) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("goodsId", goodsId);
//            map.put("skuId", skuId);
//            map.put("goodsNum", goodsNum);
//            purchaseProcessDao.addGoodsSkuCount(map);
//
//            Map<String, Object> skuInfo = mallDao.getSkuById(skuId);
//            Long mallsSkuId = (Long) skuInfo.get("mallsSkuId");
//            if(!StringUtils.isEmpty(mallsSkuId)){
//                List<Map<String, Object>> mallsGoodsSkuList = mallDao.getMallsGoodsSkuList(mallsSkuId,skuId);
//                if(null != mallsGoodsSkuList && mallsGoodsSkuList.size()>0){
//                    for (Map<String, Object> da : mallsGoodsSkuList) {
//                        Map<String, Object> mapS = new HashMap<>();
//                        mapS.put("goodsId", da.get("goodsId"));
//                        mapS.put("goodsNum", goodsNum);
//                        mapS.put("skuId", da.get("skuId"));
//                        purchaseProcessDao.addGoodsSkuCount(mapS);
//                        this.flushGoodsCache(false,Long.valueOf(da.get("goodsId").toString()),da.get("skuId").toString(),goodsNum.longValue());
//                    }
//                }
//                this.flushGoodsCache(false,mallsGoodsId,mallsSkuId.toString(),goodsNum.longValue());
//            }else {
//                this.flushGoodsCache(false,goodsId,skuId,goodsNum.longValue());
//            }
//        }
    }


    /**
     * @Modify: wuyue
     * @Date: 2019/9/5 14:22
     * @Description:确认收货后加一条dealdata记录
     * @Version: v1.8.3
     */
    public void checkReceiveOrder(Map<String, Object> params) throws GlobalException {
        Integer payMode = this.getPayModeByOrgId(params);
        params.put("payMode", payMode);
        String orderSn = "";
        if (!StringUtils.isEmpty(params.get("ordertype")) && "2".equals(params.get("ordertype").toString())) {
            mallDao.checkReceiveIntegralOrder(params);
            if (!StringUtils.isEmpty(params.get("orderId"))) {
                orderSn = integralH5Dao.getOrderSnByOrderId(Long.valueOf(params.get("orderId").toString()));
            }
        } else {
            Integer i = mallDao.checkOrderIfReceive(params);
            if (i != 0) {
                throw GlobalException.build("订单已确认");
            }
            //订单状态更新
            mallDao.checkReceiveOrder(params);
            //账单明细状态更新
            //商品所属机构栈期获取
            // 老逻辑，确认收货才会创建解冻时间，在中金支付模式下，冻结时间在支付回调的时候已经创建
            if (payMode == 0) {
                String freezeTime = mallDao.getGoodsFreezeTimeByTradeId(params);
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_YEAR, Integer.valueOf(freezeTime));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                params.put("unfreezeTime", sdf.format(calendar.getTime()));
                mallDao.updateTradeInfoByParams(params);
            }
            // 通过订单id找订单sn
            orderSn = mallDao.getOrderSnByOrderId((Integer) params.get("orderId"));
        }

        if (!StringUtils.isEmpty(orderSn)) {
            String orgId = (String) params.get("orgId");
            boolean b = purchaseProcessService.judgeOrderIfInRefundByOrderSn(orderSn);
            if (!b) {
                // 无退款，更新end_time
                String unfreezeTime = purchaseProcessService.getUnfreezeTimeByOrgId(orgId);
                purchaseProcessService.updateProtectStatusWhereAutoConfirm(orderSn, unfreezeTime);
            }
            params.put("objectId", orderSn);
        }
        if (StringUtils.isEmpty(params.get("ordertype")) || !"2".equals(params.get("ordertype").toString())) {
            this.addToDealData(params, 5);
        }
    }

    public HashMap<String, Object> getUserAddr(Map<String, Object> params) {
        return mallDao.getAddressInfo(params);
    }

    public HashMap<String, Object> getSkuInfo(Integer skuId) {
        return mallDao.getSkuInfo(skuId);
    }

    public Long addOrder(Map<String, Object> params) {
        mallDao.addOrder(params);
        Long orderId = (Long) params.get("orderId");
        return orderId;
    }

    public HashMap<String, Object> getGoodsInfo(Integer goodsId) {
        return mallDao.getGoodsInfo(goodsId);
    }

    public Integer addOrderGoods(List params) {
        return mallDao.addOrderGoods(params);
    }

    /**
     * 支付回调通知(分润)
     */
    /**
     * @Modify: wuyue
     * @Date: 2019/9/4 14:08
     * @Description:购买后为营销文库中增加购买次数
     * @Version: v1.8.3
     */
    /**
     * @Modify: wuyue
     * @Date: 2019/9/5 14:01
     * @Description: 支付完成计入DealData表
     * @Version: v1.8.3
     */
    public void orderNotifyShare(Map<String, Object> paraMap) {
        int chargeStatus = 0;
        //有支付订单，交易完成
        if (!StringUtils.isEmpty(paraMap.get("transactionId"))) {
            chargeStatus = 1;
        }
        Map<String, String> paramsMap = new HashMap<>();
        String outTradeNo = paraMap.get("outTradeNo").toString();
        String transactionId = paraMap.get("transactionId").toString();
        paramsMap.put("wxpayId", outTradeNo);
        int count = mallDao.countGoodsInfoByTradeId(paramsMap);
        if (count > 0) {
            HashMap<String, Object> outTradeNoInfo = mallDao.getOrderByPayTradeId(outTradeNo);
            paramsMap.put("status", String.valueOf(chargeStatus));
            paramsMap.put("wxtransactionId", transactionId);
            mallDao.updateMerchantOrderInfo(paramsMap);
            mallDao.updateMerchantOrderGoodsInfo(paramsMap);
            String orgId = outTradeNoInfo.get("orgId").toString();
            List<Map<String, Object>> orderGoodsList = mallDao.getOrderGoodsByOrderId(Integer.valueOf(outTradeNoInfo.get("orderId").toString()));
            String customerId = outTradeNoInfo.get("customerId").toString();
            StringBuilder goodsName = new StringBuilder();
            // 机器人开启状态
            Integer robotStatus = mallDao.getRobotStatusByOrgId(orgId);
            for (Map<String, Object> og : orderGoodsList) {
                if (og != null) {
                    Map<String, Object> ogParams = new HashMap<>();
                    ogParams.put("buyCount", Integer.parseInt(og.get("goodsNum").toString()));
                    ogParams.put("goodsId", Integer.parseInt(og.get("goodsId").toString()));
                    mallDao.editGoodSalesNum(ogParams);
                    Long goodsId = (Long) og.get("goodsId");
                    String name = mallBoomDao.getGoodsNameById(goodsId);
                    goodsName.append(name);
                    goodsName.append(",");
                    // 如果机器人开启，才加
                    if (robotStatus != null && robotStatus == 1) {
                        // 获得商品关联文章id
                        List<String> articleId = mallDao.getArticleIdByGoodsId(goodsId);
                        if (articleId != null && articleId.size() > 0) {
                            // 如果文章id不为空
                            Map<String, Object> map = new HashMap<>();
                            map.put("customerId", customerId);
                            map.put("newsId", articleId);
                            // 找到24小时内发送过的文章
                            String oneArticleId = mallDao.getArticleIdSendWithinOneDayByNewsId(map);
                            if (!StringUtils.isEmpty(oneArticleId)) {
                                mallDao.updateBuyTimesByArticleId(oneArticleId);
                            }
                        }
                    }
                }
            }
            // 新增DealData记录
            Map<String, Object> map = new HashMap<>();
            map.put("objectId", outTradeNo);
            map.put("orgId", orgId);
            map.put("customerId", customerId);
            this.addToDealData(map, 4);
            // 新增track记录
            Map<String, Object> track = new HashMap<>();
            track.put("customerId", customerId);
            String goodsNames = goodsName.toString();
            if (goodsNames.endsWith(",")) {
                goodsNames = goodsName.substring(0, goodsName.length() - 1);
            }
            track.put("goodsName", "购买了" + goodsNames);
            track.put("trackId", UUID.randomUUID().toString());
            mallBoomDao.addTrack(track);
            if (count == 1) {// 可能为麦爆商品
                MallGoodsSharePo goodsInfo = mallDao.getGoodsInfoByTradeId(paramsMap);
                //1、是否为分润商品goodsInfo.getBelongId()不为空进行分润
                if (!StringUtils.isEmpty(goodsInfo.getBelongId())) {
                    Map<String, Integer> reverseProfitModel = mallBoomDao.getReverseProfitModel(orgId);// 返润模式
                    Integer serviceRatio;// 商品服务费占比例,eg:50
                    if (reverseProfitModel == null) {
                        // 机构没有设置返润模式
                        serviceRatio = 50;
                    } else {
                        serviceRatio = reverseProfitModel.get("serviceRatio");
                    }
                    Integer rebate = goodsInfo.getRebate();// 总返利,eg:20
                    double i = rebate.doubleValue() * serviceRatio.doubleValue() / 100;// 服务费比例,eg:10
                    double j = rebate - i;// 推荐费比例,eg:10
                    double iv = goodsInfo.getGoodsAmount().doubleValue() * i / 100;// 服务费
                    double jv = goodsInfo.getGoodsAmount().doubleValue() * j / 100;// 推荐费
                    int shareTotalPrice = new BigDecimal(iv).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    int shareTotalPriceRf = new BigDecimal(jv).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
//                    int shareTotalPrice = (int) (goodsInfo.getGoodsAmount() * i / 100);// 返利值(服务费)
//                    int shareTotalPriceRf = (int) (goodsInfo.getGoodsAmount() * j / 100);// 返利值(推荐费)
                    int goodsTotalPrice = (int) (goodsInfo.getGoodsAmount() + goodsInfo.getShippingFee());// 商品价格+运费

                    String salerId = mallBoomDao.findPid(customerId);// 上级id
                    String shareId = goodsInfo.getSalerId();// 分享人id

                    boolean ifRf = !StringUtils.isEmpty(salerId) && shareTotalPriceRf != 0 && !salerId.equals(customerId);// 是否产生推荐费(true:产生,false:不产生)
                    boolean ifFw = !StringUtils.isEmpty(shareId) && shareTotalPrice != 0 && !shareId.equals(customerId);// 是否产生服务费(true:产生,false:不产生)

                    if (ifRf && ifFw) {
                        // 服务费+推荐费
                        // 商品归属获得
                        addAccountTrade("1", transactionId, outTradeNo, String.valueOf(goodsTotalPrice - shareTotalPriceRf - shareTotalPrice),
                                orgId, customerId, goodsInfo.getBelongId(), goodsInfo.getBelongId(), 0, 1);
                        // 分享人获得
                        addAccountTrade("1", transactionId, outTradeNo, String.valueOf(shareTotalPrice),
                                orgId, customerId, shareId, shareId, 1, 2);
                        // 推荐人获得
                        addAccountTrade("1", transactionId, outTradeNo, String.valueOf(shareTotalPriceRf),
                                orgId, customerId, salerId, salerId, 2, 5);
                    } else if (ifFw) {
                        // 服务费
                        // 商品归属获得
                        addAccountTrade("1", transactionId, outTradeNo, String.valueOf(goodsTotalPrice - shareTotalPrice),
                                orgId, customerId, goodsInfo.getBelongId(), goodsInfo.getBelongId(), 0, 1);
                        // 分享人获得
                        addAccountTrade("1", transactionId, outTradeNo, String.valueOf(shareTotalPrice),
                                orgId, customerId, shareId, shareId, 1, 2);
                    } else if (ifRf) {
                        // 推荐费
                        // 商品归属获得
                        addAccountTrade("1", transactionId, outTradeNo, String.valueOf(goodsTotalPrice - shareTotalPriceRf),
                                orgId, customerId, goodsInfo.getBelongId(), goodsInfo.getBelongId(), 0, 1);
                        // 推荐人获得
                        addAccountTrade("1", transactionId, outTradeNo, String.valueOf(shareTotalPriceRf),
                                orgId, customerId, salerId, salerId, 2, 5);
                    } else {
                        // 商品归属获得
                        addAccountTrade("1", transactionId, outTradeNo, String.valueOf(goodsTotalPrice),
                                orgId, customerId, goodsInfo.getBelongId(), goodsInfo.getBelongId(), 0, 1);
                    }
                    return;
                }
            }
            // 正常商品
            addAccountTrade("4", transactionId, outTradeNo, outTradeNoInfo.get("orderTotalPrice").toString(),
                    orgId, customerId, "", "",
                    0, 4);
        } else {
            LOGGER.error("未找到订单及商品对应关系===No order and commodity correspondence was found");
        }
    }

    private void addAccountTrade(String tradeType, String tradeOrderNum, String payInfo, String tradeSum, String orgId,
                                 String payUser, String reciveUser, String salerId, int belongState, int tradeSubType) {
        Map<String, Object> tradeParam = new HashMap<>();
        tradeParam.put("tradeType", tradeType);
        tradeParam.put("tradeOrderNum", tradeOrderNum);
        tradeParam.put("payInfo", payInfo);
        tradeParam.put("moneyType", "RMB");
        tradeParam.put("tradeSum", tradeSum);
        tradeParam.put("sumRmb", tradeSum);
        tradeParam.put("chargeType", "2");
        tradeParam.put("orgId", orgId);
        tradeParam.put("payUser", payUser);
        tradeParam.put("reciveUser", reciveUser);
        tradeParam.put("salerId", salerId);
        tradeParam.put("belongState", belongState);
        tradeParam.put("tradeTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        tradeParam.put("tradeSunType", tradeSubType);
        // 获取用户余额
        Long useableMoneyBelong = mallDao.getUseableMoneyByUid(reciveUser);
        tradeParam.put("reciveAccountBalance", (StringUtils.isEmpty(useableMoneyBelong) ? 0 : useableMoneyBelong) + Long.valueOf(tradeSum));
        tradeParam.put("unfreezeTime", null);
        // 查找是否有虚拟账单未结算
        Integer rebateTradeSum = mallBoomDao.getRebateTradeSum(tradeParam);
        if (rebateTradeSum != null && rebateTradeSum != 0) {
            tradeParam.put("virtualRebate", rebateTradeSum);
            // 结算完清除
            mallBoomDao.cleanRebateTradeSum(tradeParam);
        } else {
            rebateTradeSum = 0;
            tradeParam.put("virtualRebate", 0);
        }
        // 计入trade表
        mallDao.addPayTrade(tradeParam);
        if (!StringUtils.isEmpty(reciveUser)) {
            // 更新用户账户余额
            tradeParam.put("tradeSum", Long.valueOf(tradeSum) + Long.valueOf(rebateTradeSum));
            mallDao.updateAccountFreeze(tradeParam);
        }
    }

    // 递归查询某cid的父级id(mode=true只查麦)
    private String findPid(String cid, boolean mode) {
        String pid = mallBoomDao.findPid(cid);
        if (!mode) {
            return pid;
        }
        if (pid == null) {
            return null;
        }
        boolean isS = mallBoomDao.isSalerByCid(pid) == 1;
        if (isS) {
            return pid;
        } else {
            return findPid(pid, true);
        }
    }

    public Integer getPayModeByOrgId(Map<String, Object> map) {
        Integer payMode = mallDao.getPayModeByOrgId(map);
        if (payMode == null) {
            payMode = 1;
        }
        return payMode;
    }

    public Integer getPayModeByOrgId(String orgId) {
        Map<String, Object> map = new HashMap<>();
        map.put("orgId", orgId);
        return this.getPayModeByOrgId(map);
    }

    public List<Map<String, Object>> getOrderGoods(Map<String, Object> params) {
        List<Map<String, Object>> orderGoods = mallDao.getOrderGoods(params);
        for (Map<String, Object> oGoods : orderGoods) {
            oGoods.put("shippingFeeString", NumberUtils.fenToYuan(Long.valueOf(oGoods.get("shippingFee").toString())));
            Long goodsPrice = Long.valueOf(oGoods.get("goodsPrice").toString());
            oGoods.put("goodsPrice", NumberUtils.fenToYuan(goodsPrice));
            Long goodsNum = Long.valueOf(oGoods.get("goodsNum").toString());
            Long shippingFee = Long.valueOf(oGoods.get("shippingFee").toString());
            String orderTotalFee = NumberUtils.fenToYuan(goodsPrice * goodsNum + shippingFee);
            oGoods.put("orderTotalFee", orderTotalFee);
        }
        return orderGoods;
    }

    public void applyRefund(Map<String, Object> params) {
        String recIds = params.get("recIds").toString();
        String[] rIds = recIds.split(",");
        Object refundImagesTemp = params.get("refundImages");
        Object refundImages = params.get("refundImages");
        if (!StringUtils.isEmpty(refundImages)) {
            params.put("refundImages", JSONArray.toJSONString(refundImages));
        }
        String refundWay = "";
        if (0 == (Integer) params.get("refundWay")) {
            refundWay = "仅退款";
        }
        if (1 == (Integer) params.get("refundWay")) {
            refundWay = "退货退款";
        }
        Set<String> phoneLists = new HashSet<>();
        for (String rid : rIds) {
            params.put("recId", rid);
//            params.put("orderId", orderId);
            Map<String, Object> orderGoodsInfo = mallDao.getOrderGoodsInfoByOid(params);
            Integer orderId = Integer.valueOf(orderGoodsInfo.get("orderId").toString());
            String orderSn = mallDao.getOrderSnByOrderId(orderId);
            String isEnd = mallDao.getIsEndByOrderSn(orderSn);
            if ("1".equals(isEnd)) {
                throw GlobalException.build("已选商品中有已结算完成的商品，操作失败。");
            }
            String refundStatus = orderGoodsInfo.get("refundStatus").toString();
            if (!"0".equals(refundStatus) && !"7".equals(refundStatus)) {
                continue;
            }
            boolean isAdd = true;
            if ("7".equals(refundStatus)) {
                isAdd = false;
            }
            String gid = orderGoodsInfo.get("goodsId").toString();
            long time = System.currentTimeMillis();
            String protectCode = "wq" + time + gid + params.get("customerId");

            params.put("protectCode", protectCode);
            mallDao.saveOrderGoodsRefund(params);
            //是否是修改 1是，0或不传不是
            if (isAdd) {
                protectRecordService.addRefund(params.get("orderSn").toString(), Long.valueOf(orderGoodsInfo.get("recId").toString()),
                        Long.valueOf(orderGoodsInfo.get("goodsPrice").toString()), Long.valueOf(orderGoodsInfo.get("goodsNum").toString()),
                        Long.valueOf(orderGoodsInfo.get("shippingFee").toString()));
            }

            Map<String, Object> consult = new HashMap<>();
            Map<String, Object> orderGoodsInfoNew = mallDao.getOrderGoodsInfoByOid(params);
            consult.put("recId", orderGoodsInfoNew.get("recId"));
            consult.put("protectCode", orderGoodsInfoNew.get("protectCode"));
            consult.put("consultStatus", "买家发起退货申请");
            Integer goodsPrice = Integer.parseInt(orderGoodsInfoNew.get("goodsPrice").toString());
            Integer goodsNum = Integer.valueOf(orderGoodsInfoNew.get("goodsNum").toString());
            Integer shippingFee = Integer.valueOf(orderGoodsInfoNew.get("shippingFee").toString());
            Integer couponAmount = Integer.valueOf(orderGoodsInfoNew.get("couponAmount").toString());
            Integer reMoney = goodsPrice * goodsNum + shippingFee - couponAmount; //单价*数量+运费
            String refundAmount = NumberUtils.fenToYuan(Long.valueOf(reMoney));
            String content = "退款原因：" + params.get("refundReason") + "\n" +
                    "处理方式：" + refundWay + "\n" +
                    "退款金额：" + refundAmount + "\n" +
                    "退款说明：" + params.get("refundDescribe") + "\n" +
                    "联系电话：" + params.get("refundPhone");
            consult.put("consultContent", content);
            consult.put("consultImages", refundImagesTemp);
            maiBaoLaService.addConsult(consult);
            // 查找商品对应的商家手机号 （可能存在多个商家）
            String sallerPhone = maiBaoLaService.getRemindPhoneByGid(gid);
            if (!StringUtils.isEmpty(sallerPhone)) {
                phoneLists.add(sallerPhone);
            }
        }

        Long refundAmount1 = mallDao.getGoodsAmountByIds(params);//订单中退款金额
        Integer refundAmount = Integer.valueOf(refundAmount1.toString());
        String orderId = mallDao.getOrderIdByOrderSn(params.get("orderSn").toString());
        Integer orderGoodsCountByOrderSn = mallDao.getOrderGoodsCountByOrderSn(orderId);
        Integer refundState = 1;//订单中部分退款
        if (orderGoodsCountByOrderSn == rIds.length) {
            refundState = 2;//订单中全部退款
        }
        Map<String, Object> orderData = new HashMap<>();
        orderData.put("refundState", refundState);
        orderData.put("orderSn", params.get("orderSn"));
        orderData.put("refundAmount", refundAmount);
        mallDao.saveOrderRefund(orderData);

        //  发生提醒短信
        try {
            String orgId = params.get("orgId").toString();
            Map<String, Object> nvps = new HashMap<>();
            nvps.put("businessType", 9011);
            String publicName = maiBaoLaDao.getPublicNameByOrgId(orgId);
            nvps.put("params", "{name=" + publicName + "公众号}");
            // 取出集合中的每个元素
            for (String phone : phoneLists) {
                nvps.put("mobilNumber", phone);
                String result = smsService.sendMsg(orgId, nvps);
                LOGGER.info("审核短信发送结果===" + result);
            }
        } catch (Exception e) {
            LOGGER.info("短信网关错误===" + e);
        }
    }

    public Map<String, Object> getRefundAmount(Map<String, Object> param) {
        String bindPhone = mallBoomDao.getBindPhoneByCid(param.get("customerId").toString());
        String orderSn = param.get("orderSn").toString();
        Map<String, Object> orderInfo = mallDao.getOrderInfoBySn(orderSn);
        Integer integralPaymentAmount = Integer.valueOf(orderInfo.get("integralPaymentAmount").toString());//金币抵扣金额
        Integer orderTotalPrice = Integer.valueOf(orderInfo.get("orderTotalPrice").toString());//订单总金额
        Integer goodsAmount2 = 0;
        Integer coin = 0;
        if (orderTotalPrice > 0) {
            BigDecimal bigDecimal = new BigDecimal(integralPaymentAmount).divide(new BigDecimal(orderTotalPrice), 5, BigDecimal.ROUND_HALF_EVEN);

            Long goodsAmount1 = mallDao.getGoodsAmountByIds(param);//退货金额
            goodsAmount2 = Integer.valueOf(goodsAmount1.toString());
            coin = bigDecimal.multiply(new BigDecimal(goodsAmount2)).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
        }

        Map<String, Object> data = new HashMap<>();
        data.put("bindPhone", bindPhone);
        data.put("goodsAmount", NumberUtils.fenToYuan(Long.valueOf(goodsAmount2)));
        data.put("coinAmount", NumberUtils.fenToYuan(Long.valueOf(coin > 0 ? coin : 0)));
        return data;
    }

    public List<Map<String, Object>> getOrderGoodsInfo(Map<String, Object> param) {
        String orderSn = (String) param.get("orderSn");
        if (orderSn.startsWith("I")) {
            List<Map<String, Object>> orderGoodsInfo = mallDao.getIntegralOrderGoodsInfo(param);
            for (Map<String, Object> da : orderGoodsInfo) {
                da.put("orderSn", param.get("orderSn"));
                da.put("orderGoodsList", mallDao.getIntegralOrderGoodsByShipping(da));
            }
            return orderGoodsInfo;
        } else {
            List<Map<String, Object>> orderGoodsInfo = mallDao.getOrderGoodsInfo(param);
            for (Map<String, Object> da : orderGoodsInfo) {
                da.put("orderSn", param.get("orderSn"));
                da.put("orderGoodsList", mallDao.getOrderGoodsByShipping(da));
            }
            return orderGoodsInfo;
        }
    }

    public void editOrderAddress(Map<String, Object> param) {
        OrderAddressDto orderAddressDto = mallDao.getDefaultReceiveAddress(param);
        if (orderAddressDto == null) {
            throw GlobalException.build("地址不存在或用户与地址不匹配");
        }
        param.put("addressRealName", orderAddressDto.getRealName());
        param.put("addressPhone", orderAddressDto.getPhone());
        param.put("addressProvince", orderAddressDto.getProvinceName());
        param.put("addressCity", orderAddressDto.getCityName());
        param.put("addressArea", orderAddressDto.getAreaName());
        param.put("addressDetailedAddress", orderAddressDto.getAddressInfo());
        if ("2".equals(param.get("ordertype").toString())) {
            mallDao.editIntegralOrderAddress(param);
        } else {
            mallDao.editOrderAddress(param);
        }
    }

    public Object getPayStatus(Map<String, Object> param) {
        String goodsType;
        String orderSn = "";
        if (!StringUtils.isEmpty(param.get("orderSn"))) {
            orderSn = param.get("orderSn").toString();
        }
        if (!StringUtils.isEmpty(param.get("goodsType")) || orderSn.startsWith("I")) {
            goodsType = param.get("goodsType").toString();
        } else {
            throw GlobalException.build("参数错误！");
        }
        if (orderSn.startsWith("I")) {
            goodsType = "6";
        }
        Integer paymentState = 0;
        if ("1".equals(goodsType)) {
            //商品
            paymentState = mallDao.getPayStatus(param);
        } else if ("2".equals(goodsType)) {
            //报名
            paymentState = mallDao.getEnrollPayStatus(param);
        } else if ("3".equals(goodsType) || "4".equals(goodsType)) {
            //开通 3开通联盟商家 4开通加盟代理
            paymentState = mallDao.getSalerPayStatus(param);
        } else if ("5".equals(goodsType)) {
            paymentState = mallDao.getVipPayStatus(param);
        } else if ("6".equals(goodsType)) {
            paymentState = mallDao.getIntegralPayStatus(param);
        } else if ("7".equals(goodsType)) {
            Map<String, Object> customerRecord = (Map) this.formRequest.doRequest("/h5/form/getRecordByOrderSn", param, null);
            if (null != customerRecord) {
                paymentState = Integer.valueOf(customerRecord.get("payStatus").toString());
            }
        }

        return paymentState == null ? 0 : paymentState;
    }


    public Map<String, Object> getMallDetail(String shippingCode, String orderSn) {
        String goodsId = "";
        if (orderSn.startsWith("I")) {
            String orgId = mallDao.getIntegralGoodsIdByShippingCode(shippingCode, orderSn);
            if (StringUtils.isEmpty(orgId)) {
                throw GlobalException.build("运单号参数错误");
            }
            Map<String, Object> param = new HashMap<>();
            param.put("orgId", orgId);
            param.put("integral", 1);
            return mallDao.getMallDetail(param);
        } else {
            goodsId = mallDao.getGoodsIdByShippingCode(shippingCode, orderSn);
        }
        if (StringUtils.isEmpty(goodsId)) {
            throw GlobalException.build("运单号参数错误");
        }
        Map goodsInfo = goodsService.getGoodsInfo(goodsId);
        if (!StringUtils.isEmpty(goodsInfo.get("mallsGoodsId"))) {
            goodsInfo = goodsService.getGoodsInfo(goodsInfo.get("mallsGoodsId").toString());
        }
        Map<String, Object> param = new HashMap<>(2);
        param.put("orgId", goodsInfo.get("orgId"));
        param.put("belongId", goodsInfo.get("belongId"));
        return mallDao.getMallDetail(param);
    }


    public void flushCartGoodsSkuInfo(Long goodsId) {

        String goodsInfoKey = CrmRedisKeys.GOODS_INFO_KEY + goodsId;
        redisTemplate.delete(goodsInfoKey);
        String skuInfoKey = CrmRedisKeys.GOODS_SKU_INFO_KEY + goodsId;
        redisTemplate.delete(skuInfoKey);

        String goodsSkuOldKey = CrmRedisKeys.cartGoodsSkuInfoKey + goodsId + "*";
        Set<String> gskeys = redisTemplate.keys(goodsSkuOldKey);
        redisTemplate.delete(gskeys);

        //region 因为缓存我直接用了goodsinfo下的缓存信息所以这些缓存不用再删了也不会写入 ckq 2020-07-13
//        String orderGoodsInfoKey = PurchaseProcessNewService.ORDER_GOODS_INFO + goodsId;
//        redisTemplate.delete(orderGoodsInfoKey);
//        String orderMallGoodsSkuIdKey = PurchaseProcessNewService.ORDER_MALL_GOODS_SKUID + goodsId + "*";
//        Set<String> orderMallGoodsSkuIdKeys = redisTemplate.keys(orderMallGoodsSkuIdKey);
//        redisTemplate.delete(orderMallGoodsSkuIdKeys);
//        String orderGoodsPriceKey = PurchaseProcessNewService.ORDER_GOODS_PRICE + goodsId + "*";
//        Set<String> orderGoodsPriceKeys = redisTemplate.keys(orderGoodsPriceKey);
//        redisTemplate.delete(orderGoodsPriceKeys);
        //endregion
    }

    public void flushGoodsCache(boolean isDel, Long goodsId, String skuId, Long goodsCount) {
        if (isDel) {
            String goodsInfoKey = CrmRedisKeys.GOODS_INFO_KEY + goodsId;
            redisTemplate.delete(goodsInfoKey);
            String skuInfoKey = CrmRedisKeys.GOODS_SKU_INFO_KEY + goodsId;
            redisTemplate.delete(skuInfoKey);
            String specInfoKey = CrmRedisKeys.GOODS_SPEC_INFO_KEY + goodsId;
            redisTemplate.delete(specInfoKey);
            String goodsCountKey = CrmRedisKeys.goodsCountKey + goodsId;
            redisTemplate.delete(goodsCountKey);
            String skuCountOldKey = CrmRedisKeys.skuCountKey + goodsId + "_*";
            Set<String> keys = redisTemplate.keys(skuCountOldKey);
            redisTemplate.delete(keys);
            String goodsSkuOldKey = CrmRedisKeys.cartGoodsSkuInfoKey + goodsId + "*";
            Set<String> gskeys = redisTemplate.keys(goodsSkuOldKey);
            redisTemplate.delete(gskeys);

            //region 因为缓存我直接用了goodsinfo下的缓存信息所以这些缓存不用再删了也不会写入 ckq 2020-07-13
//            String orderGoodsInfoKey = PurchaseProcessNewService.ORDER_GOODS_INFO + goodsId;
//            redisTemplate.delete(orderGoodsInfoKey);
//            String orderMallGoodsSkuIdKey = PurchaseProcessNewService.ORDER_MALL_GOODS_SKUID + goodsId + "*";
//            Set<String> orderMallGoodsSkuIdKeys = redisTemplate.keys(orderMallGoodsSkuIdKey);
//            redisTemplate.delete(orderMallGoodsSkuIdKeys);
//            String orderGoodsPriceKey = PurchaseProcessNewService.ORDER_GOODS_PRICE + goodsId + "*";
//            Set<String> orderGoodsPriceKeys = redisTemplate.keys(orderGoodsPriceKey);
//            redisTemplate.delete(orderGoodsPriceKeys);
            //endregion

        } else {
            if (goodsCount > 0) {
                if (StringUtils.isEmpty(skuId)) {
                    String goodsCountKey = CrmRedisKeys.goodsCountKey + goodsId;
                    redisTemplate.opsForValue().increment(goodsCountKey, goodsCount);
//                    ArrayList<String> goodsList = new ArrayList<>(Collections.nCopies(goodsCount.intValue(),"1"));
//                    redisTemplate.opsForList().leftPushAll(goodsCountKey, goodsList);
                } else {
                    String skuCountKey = CrmRedisKeys.skuCountKey + goodsId + "_" + skuId;
                    redisTemplate.opsForValue().increment(skuCountKey, goodsCount);
//                    ArrayList<String> skuList = new ArrayList<>(Collections.nCopies(goodsCount.intValue(),"1"));
//                    redisTemplate.opsForList().leftPushAll(skuCountKey, skuList);
                }
            }
        }
    }

    public List<Map<String, Object>> getIntegralGoodslist(String orgId, Integer goodsType, Long groupId) {
        return mallDao.getIntegralGoodslist(orgId, goodsType,groupId);
    }

    public Object getIntegralLogList(Map<String, Object> param) {
        String customerId = param.get("customerId").toString();
        String orgId = param.get("orgId").toString();
        String integralFieldName = IntegralEnums.customerScore.toString();
        Integer pageIndex = Integer.valueOf(param.get("pageIndex").toString());
        Integer pageSize = Integer.valueOf(param.get("pageSize").toString());
        return this.customerIntegralService.getIntegralCustomerLogs(customerId, orgId, integralFieldName, pageIndex, null, pageSize);
    }

    public List<Map<String, Object>> getIntegralOrderList(String customerId) {
        return mallDao.getIntegralOrderList(customerId);
    }

    public Object getRefundList(Map<String, Object> params) {
        List<MerchantRefundGoodsPo> goodsPoList = new ArrayList<>();
        Integer pageIndex = (Integer) params.get("pageIndex");
        if (StringUtils.isEmpty(pageIndex) || pageIndex < 1) {
            pageIndex = 1;
        }
        int perPage = 20;
        int count = mallDao.getUserFundCount(params);
        if (count > 0) {
            PageHelper.startPage(pageIndex, perPage);
//            List<MerchantRefundGoodsPo> list2 = mallDao.getMerchantOrderGoodsList(params);
            goodsPoList = mallDao.getMerchantRefundGoodsList(params);

            for (MerchantRefundGoodsPo refundGoodsPo : goodsPoList) {
                String belongId = refundGoodsPo.getBelongId();
                Map map = merchantService.getMerchantDetail(belongId, refundGoodsPo.getOrgId());
                String storeName = "";
                if (!StringUtils.isEmpty(map.get("storeName"))) {
                    storeName = map.get("storeName").toString();
                }
                refundGoodsPo.setStoreName(storeName);
                if (refundGoodsPo.getRefundStatus() == 5 || refundGoodsPo.getRefundStatus() == 6) {
                    refundGoodsPo.setRefundStatus(2);
                } else {
                    refundGoodsPo.setRefundStatus(1);
                }
            }
        }
        return new PageInfo<>(goodsPoList);
    }

    public List<Map<String, Object>> getGoodsService(Integer goodsId) {
        return mallDao.getGoodsService(goodsId);
    }

    public List<Map<String, Object>> getIntegralLogListByLocal(Map<String, Object> param) {
        List<Map<String, Object>> list = mallDao.getIntegralLogListByLocal(param);
        if (list != null && list.size() > 0) {
            for (Map info : list) {
                Integer scoreType = 0;
                String behavior = "系统赠送";
                if (!StringUtils.isEmpty(info.get("scoreType"))) {
                    scoreType = Integer.valueOf(info.get("scoreType").toString());
                }
                Long score = 0L;
                if (!StringUtils.isEmpty(info.get("score"))) {
                    score = Long.valueOf(info.get("score").toString());
                }
                switch (scoreType) {
                    case 0:
                        behavior = "系统赠送";
                        if (score < 0) {
                            behavior = "系统扣除";
                        }
                        break;
                    case 1:
                        behavior = "文章点赞";
                        break;
                    case 2:
                        behavior = "文章转发";
                        break;
                    case 3:
                        behavior = "文章评论";
                        break;
                    case 4:
                        behavior = "礼包奖励";
                        break;
                    case 5:
                        behavior = "升级奖励";
                        break;
                    case 6:
                        behavior = "兑换商品";
                        break;
                    case 7:
                        behavior = "购买商品赠送";
                        break;
                    case 8:
                        behavior = "完成下单赠送";
                        break;
                    case 9:
                        behavior ="分享成交";
                        break;
                    case 10:
                        behavior="邀请注册";
                        break;
                    case 11:
                        behavior="分享关注公众号";
                        break;
                    case 12:
                        behavior="分享传播";
                        break;
                    case 13:
                        behavior="注册赠送";
                        break;
                    default:
                        behavior = "系统赠送";
                        break;
                }
                info.put("behavior", behavior);
            }
        }
        return list;
    }


    public List<Map> getIntegralGrouplist(String orgId) {
        List<Map> grouplist = mallDao.getIntegralGrouplist(orgId);
        List<Map> reslist = new ArrayList<>();
        if(grouplist!=null && grouplist.size()>0){
            for(Map group : grouplist){
                group.put("orgId",orgId);
                List<Map> groupGoodslist = mallDao.getIntegralGroupGoodslist(group);
                if(groupGoodslist!=null && groupGoodslist.size()>0){
                    group.put("goodsList",groupGoodslist);
                    reslist.add(group);
                }
            }
        }
        return reslist;
    }
}
